package com.appcenter.application.service;

import com.appcenter.application.dto.apps.AppDto;
import com.appcenter.application.dto.orgJobs.GetOrgJobsDto;
import com.appcenter.application.dto.permissiongrouprelations.CreatePermissionGroupRelationDto;
import com.appcenter.application.dto.permissiongrouprelations.PermissionGroupRelationDto;
import com.appcenter.application.dto.permissiongroups.PermissionGroupDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.app.GetAppsInput;
import com.appcenter.application.input.permissiongroup.*;
import com.appcenter.application.input.permissiongrouprelation.CreatePermissionGroupRelationInput;
import com.appcenter.application.mapper.AppsMapper;
import com.appcenter.application.mapper.PermissionGroupRelationsMapper;
import com.appcenter.application.mapper.PermissionGroupsMapper;
import com.appcenter.application.mapper.PermissionRelationsMapper;
import com.appcenter.application.model.Apps;
import com.appcenter.application.model.PermissionGroupRelations;
import com.appcenter.application.model.PermissionGroups;
import com.appcenter.application.output.permissiongroup.*;
import com.appcenter.application.output.permissiongrouprelation.CreatePermissionGroupRelationOutput;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.jz.unit.ObjectUnit;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PermissionGroupService {
    @Autowired
    PermissionGroupsMapper permissionGroupsMapper;
    @Autowired
    PermissionGroupRelationsMapper permissionGroupRelationsMapper;

    @Autowired
    PermissionRelationsMapper permissionRelationsMapper;
    @Autowired
    AppsMapper appsMapper;

    @Autowired
    ObjectFinal objectFinal;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 加载权限组
     *  时间: 2019/4/26 14:00 
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output=new PageLoadOutput();
        GetAppsInput getAppsInput=new GetAppsInput();
        List<AppDto> apps = objectFinal.GetPermissionApps(ObjectFinal.APP_CODE,CurrentUser.getUserCode());
        output.setApps(apps);

        if ( apps!=null && apps.size()>0) {
            GetPermissionGroupsOutput getPermissionGroupsOutput=GetPermissionGroups(input);
            output.setItems(getPermissionGroupsOutput.getItems());
        }
        return output;
    }

//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 获取权限组信息
     *  时间: 2019/4/26 14:01 
     *  参数: 
     */
    public GetPermissionGroupsOutput GetPermissionGroups(GetPermissionGroupsInput input) throws Exception {
        GetPermissionGroupsOutput output=new GetPermissionGroupsOutput();

        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"listOrder asc");
        List<PermissionGroups>  permissionGroups= permissionGroupsMapper.GetPermissionGroups(input);
        PageInfo<PermissionGroups> page = new PageInfo<>(permissionGroups);
        List<PermissionGroupDto> ls=new ArrayList<>();
        for(PermissionGroups permissionGroup:page.getList()) {
            PermissionGroupDto permissionGroupDto=new PermissionGroupDto();
            BeanUtils.copyProperties(permissionGroup,permissionGroupDto);
            permissionGroupDto.setPermissionGroupRelations(permissionGroupRelationsMapper.getPermissionGroupRelationByGroupId(permissionGroupDto.getId()));
            ls.add(permissionGroupDto);
        }
        output.setItems(new PagedResult<PermissionGroupDto>(ls, (int) page.getTotal()));

        BusinessLogger.Info(LoggerGenre.View,"获取权限组",input);
       return output;
    }
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 创建权限组信息
     *  时间: 2019/4/26 14:01 
     *  参数: 
     */
    public CreatePermissionGroupOutput CreatePermissionGroup(CreatePermissionGroupInput input) throws Exception {
        CreatePermissionGroupOutput output=new CreatePermissionGroupOutput();
        PermissionGroupDto permissionGroupDto=input.getItem();

        Example example = new Example(PermissionGroups.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("appId", permissionGroupDto.getAppId());
        criteria.andEqualTo("permissionGroupCode", permissionGroupDto.getPermissionGroupCode());
        criteria.andEqualTo("validStatus",true);
       int count = permissionGroupsMapper.selectCountByExample(example);
        if (count>0) {
            throw new ErrorJsonResult("1000031", "权限组编号不能重复！");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        permissionGroupDto.setId(uuid);
        permissionGroupDto.setCreateTime(new Date());
        permissionGroupDto.setCreateUserId(CurrentUser.getUserId());
        permissionGroupDto.setValidStatus(true);

        PermissionGroups permissionGroup=new PermissionGroups();
        BeanUtils.copyProperties(permissionGroupDto,permissionGroup);

        BusinessLogger.Info(LoggerGenre.Add,"添加权限组",input);
        permissionGroupsMapper.insertSelective(permissionGroup);
        output.setItem(permissionGroupDto);
        return output;
    }

//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 修改权限组信息
     *  时间: 2019/4/26 14:01 
     *  参数: 
     */
    public EditPermissionGroupOutput EditPermissionGroup(EditPermissionGroupInput input) throws Exception {
        EditPermissionGroupOutput output=new EditPermissionGroupOutput();
        PermissionGroupDto permissionGroupDto=input.getItem();

        Example example = new Example(PermissionGroups.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("appId", permissionGroupDto.getAppId());
        criteria.andEqualTo("permissionGroupCode", permissionGroupDto.getPermissionGroupCode());
        criteria.andNotEqualTo("id",permissionGroupDto.getId());
        criteria.andEqualTo("validStatus",true);
        int count = permissionGroupsMapper.selectCountByExample(example);

        if (count>0) {
            throw new ErrorJsonResult("1000031", "权限组编号不能重复！");
        }
        PermissionGroups permissionGroup=permissionGroupsMapper.selectByPrimaryKey(permissionGroupDto.getId());
        permissionGroup.setPermissionGroupName(permissionGroupDto.getPermissionGroupName());
        permissionGroup.setPermissionGroupCode(permissionGroupDto.getPermissionGroupCode());
        permissionGroup.setListOrder(permissionGroupDto.getListOrder());

        BusinessLogger.Info(LoggerGenre.Update,"编辑权限组",input);
        permissionGroupsMapper.updateByPrimaryKey(permissionGroup);
        BeanUtils.copyProperties(permissionGroup,permissionGroupDto);
        output.setItem(permissionGroupDto);
        return output;
    }

//    @CacheEvict(cacheNames="basewarrant", allEntries=true)
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 删除权限组信息
     *  时间: 2019/4/26 14:01 
     *  参数: 
     */
    public DeletePermissionGroupOutput DeletePermissionGroup(DeletePermissionGroupInput input) throws Exception {
        DeletePermissionGroupOutput output=new DeletePermissionGroupOutput();
        //删除权限组权限
        PermissionGroups permissionGroup=permissionGroupsMapper.selectByPrimaryKey(input.getItem().getId());
        permissionGroup.setValidStatus(false);

        //删除权限组下关联的权限
        Example exampleGroupRelation = new Example(PermissionGroupRelations.class);
        Example.Criteria criteriaGroupRelation = exampleGroupRelation.createCriteria();
        criteriaGroupRelation.andEqualTo("permissiongroupId",permissionGroup.getId());
        permissionGroupRelationsMapper.deleteByExample(exampleGroupRelation);

        //删除权限组 的落地权限
        Example examplePermissionRelation = new Example(PermissionGroupRelations.class);
        Example.Criteria criteriaPermissionRelation = examplePermissionRelation.createCriteria();
        criteriaPermissionRelation.andEqualTo("permissionId",permissionGroup.getId());
        permissionRelationsMapper.deleteByExample(examplePermissionRelation);

        permissionGroupRelationsMapper.deleteByExample(exampleGroupRelation);
        BusinessLogger.Info(LoggerGenre.Delete,"删除权限组",input);
        permissionGroupsMapper.updateByPrimaryKey(permissionGroup);
        PermissionGroupDto permissionGroupDto=input.getItem();
        BeanUtils.copyProperties(permissionGroup,permissionGroupDto);
        output.setItem(permissionGroupDto);
        return output;
    }

//    @CacheEvict(cacheNames="basewarrant", allEntries=true)
//    @Transactional
    /**
     *  创建人:Coke
     *  备注: 创建权限组权限信息
     *  时间: 2019/4/26 14:13
     *  参数: 
     */
    public CreatePermissionGroupRelationOutput CreatePermissionGroupRelation(CreatePermissionGroupRelationInput input) throws Exception {
        CreatePermissionGroupRelationOutput output=new CreatePermissionGroupRelationOutput();
        CreatePermissionGroupRelationDto createPermissionGroupRelationDto=input.getItem();
        //删除权限组之前的权限
        Example example = new Example(PermissionGroupRelations.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("permissiongroupId",createPermissionGroupRelationDto.getPermissiongroupId());
        List<PermissionGroupRelations> oldPermissionGroupRelations=permissionGroupRelationsMapper.selectByExample(example);
            for (PermissionGroupRelations oldPermissionGroupRelation : oldPermissionGroupRelations) {
                permissionGroupRelationsMapper.delete(oldPermissionGroupRelation);
            }
        //添加权限组新的权限
        for(PermissionGroupRelationDto permissionGroupRelationDto:createPermissionGroupRelationDto.getPermissionGroupRelations()) {
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            permissionGroupRelationDto.setId(uuid);
            PermissionGroupRelations permissionGroupRelation=new PermissionGroupRelations();
            BeanUtils.copyProperties(permissionGroupRelationDto,permissionGroupRelation);
            permissionGroupRelationsMapper.insertSelective(permissionGroupRelation);
        }
        BusinessLogger.Info(LoggerGenre.Add,"权限组设置权限",input);
        output.setItem(createPermissionGroupRelationDto);
        return output;
    }
}
